package rm.mk.data;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

public class DataBase {

	private static final String fileName = "/routes.csv";

	public List<City> readAllRoutes() {
		URI newPath = null;
		List<City> cities = new ArrayList<City>();

		try {
			newPath = this.getClass().getResource(fileName).toURI();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String sCurrentLine;

		BufferedReader br = null;

		try {
			br = new BufferedReader(new FileReader(newPath.getPath()));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		int line = 0;
		try {
			while ((sCurrentLine = br.readLine()) != null) {
				if (sCurrentLine.startsWith("#"))
					continue;
				else {
					String[] splitted = sCurrentLine.split(";");

					City c = getCity(cities, splitted[0]);
					
					c.addRoute(new Route(splitted[1], splitted[2]));
				}
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return cities;
	}

	private City getCity(List<City> cities, String string) {
		int cityNr = Integer.parseInt(string);

		City ret = null;

		for (City c : cities)
			if (c.getCityNr() == cityNr) {
				ret = c;
				break;
			}
		
		if(ret == null)
		{
			ret = new City(cityNr);
			cities.add(ret);
		}
		
		return ret;
	}
}
